const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  let body = event;
  if (event.body != undefined) {
    body = JSON.parse(event.body)
  }

  const uniIDIns = uniID.createInstance({ context })
  const db = uniCloud.database()

  try {
    // 1. 身份验证
    const { uid } = await uniIDIns.checkToken(body.uniIdToken)
    if (!uid) {
      return { code: 403, msg: '咨询师身份验证失败' }
    }

    let { appointUserId } = body;
    if (!appointUserId) {
      return { code: 403, msg: '缺少参数 appointUserId' }
    }

    // 2. 查询 appoint_schedule
    const appointRes = await db.collection('appoint_schedule')
      .where({
        consultant: uid,
        uid: appointUserId
      })
      .get()

    if (appointRes.data.length === 0) {
      return { code: 404, msg: '没有符合条件的 appoint_schedule 记录' }
    }

    const { day, appointedSlot, _id } = appointRes.data[0];

    // 3. 查询 goeasy_messages
    const messagesRes = await db.collection('goeasy_messages')
      .where({
        $or: [
          { senderId: uid, receiverId: appointUserId },
          { senderId: appointUserId, receiverId: uid }
        ]
      })
      .get()

    if (messagesRes.data.length === 0) {
      return { code: 404, msg: '没有符合条件的消息记录' }
    }

    // 4. 整理消息文本
    let resultText = `咨询师ID: ${uid}\n用户ID: ${appointUserId}\n\n`
    for (let msg of messagesRes.data) {
      const senderName = msg.senderId === uid ? '咨询师' : (msg.senderId === appointUserId ? '用户' : '未知发送者');
      const payload = JSON.parse(msg.payload).text;
      if (msg.senderId === uid || msg.senderId === appointUserId) {
        resultText += `${senderName}：${payload}\n`;
      }
    }

    // 5. 上传聊天记录至云存储
    const folderPath = `consultation_logs/${uid}/`;
    const fileName = `${appointUserId}_${day}_${appointedSlot.replace(':', '-')}.txt`;
    const cloudPath = folderPath + fileName;

    const uploadRes = await uniCloud.uploadFile({
      cloudPathAsRealPath: true,
      cloudPath,
      fileContent: Buffer.from(resultText, 'utf-8')
    });

    // 6. 检查 appoint_records 中是否已有匹配记录
    const recordRes = await db.collection('appoint_records')
      .where({
        consultant: uid,
        user: appointUserId,
        day,
        appointedSlot
      })
      .get();

    if (recordRes.data.length > 0) {
      // 已存在，更新 file_path
      const recordId = recordRes.data[0]._id;
      await db.collection('appoint_records').doc(recordId).update({
        file_path: uploadRes.fileID,
        update_time: new Date()
      });
    } else {
      // 不存在，新增记录
      await db.collection('appoint_records').add({
        consultant: uid,
        user: appointUserId,
        day,
        appointedSlot,
        file_path: uploadRes.fileID,
        created_at: Date.now(),
        update_time: new Date()
      });
    }
	
    // 6.1 减少咨询师的 required_number（仅当大于0时）
    const userCollection = db.collection('uni-id-users');
    const userRes = await userCollection.doc(uid).get();
    const requiredNumber = userRes.data[0]?.required_number ?? 0;

    if (requiredNumber > 0) {
      await userCollection.doc(uid).update({
        required_number: db.command.inc(-1)
      });
    }
	
    // 7. 删除 appoint_schedule
    await db.collection('appoint_schedule').doc(_id).remove();

    // 8. 删除 goeasy_messages 中相关记录
    await db.collection('goeasy_messages')
      .where({
        appointId: _id
      })
      .remove();

    return {
      code: 0,
      msg: '聊天记录已生成并写入/更新数据库',
      file_path: uploadRes.fileID
    }

  } catch (e) {
    return { code: 500, msg: '服务器错误', detail: e.message }
  }
}
